// pages/Apply_return/Apply_return.js
import api from '../../Sendingmethod/Sendingmethod'
import {
    Bseurl
} from "../../baseurl/baseurl"
import
encrypt
from "../../utils/crypto-util.js"
import util from '../../utils/util'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        goodslist: [],
        tailsimg: '',
        actions: [{
                name: '退货订单',
                kephone: 1
            },
            {
                name: '货损报备',
                kephone: 2
            },
        ],
        actions1: [{
                name: '需要退货',
                kephone: 1
            },
            {
                name: '无需退货',
                kephone: 0
            },
        ],
        showon: false,
        textpe: "请选择类型",
        textpe1: "请选择类型",
        objdata: {
            order_type: "",
            describe: "",
            image: "",
            goods_need_return: "",
        },

        maskblen: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },
    onCancel() {
        this.setData({
            showon: false
        })

    },
    onCancel1() {
        this.setData({
            showon1: false
        })

    },
    /**
     * 
     * 判断
     */
    panduan() {
        function getEmptyProperties(obj) {
            return Object.keys(obj).filter(key => obj[key] === "");
        }

        let num = getEmptyProperties(this.data.objdata);


        console.log(num, '空的个数');
        let blen = this.hasPositiveNum(this.data.goodslist)

        if (num.length> 0) {
            
            this.setData({
                maskblen: false
            })
        } else {
                if (this.data.objdata.goods_need_return == 0) {
                    this.setData({
                        maskblen: true
                    })
                } else {
                    if (blen) {
                        console.log('至少有一个品类选中');
                        this.setData({
                            maskblen: true
                        })
                    } else {
                        this.setData({
                            maskblen: false
                        })
                        console.log('不放行');
                    }
                }
            // } else {
               
            // }
            
        }

    },
    btntab(e) {
        console.log(e, '类型选择');
        this.setData({
            showon: false,
            textpe: e.detail.name,
            ['objdata.order_type']: e.detail.kephone
        })
        this.panduan()
    },
    btntab1(e) {
        console.log(e, '类型选择');
        this.setData({
            showon1: false,
            textpe1: e.detail.name,
            ['objdata.goods_need_return']: e.detail.kephone
        })
        this.panduan()
    },
    dakaini() {
        this.setData({
            showon: true
        })
    },
    dakaini1() {
        this.setData({
            showon1: true
        })
    },
    goto() {
        wx.navigateTo({
            url: '/pages/submit_order/submit_order',
        })
    },
    /**
     * 输入
     */
    inputbox(e) {
        console.log(e);
        this.setData({
            ['objdata.describe']: e.detail.value
        })
        this.panduan()
    },
    /**
     * 获取我的商品信息
     */
    async shopdeteil() {
        let res = await api.myreturnGoodsList()
        console.log(res, '我的商品列表');
        if (res.code == 0) {
            let data = res.data.map((item) => {
                return {
                    ...item,
                    num: 0,
                    amout: 0
                }
            })
            this.setData({
                goodslist: data
            })
        }
    },
    /**
     * 
     * 图片上传
     */
    updateimg(e) {
        let _that = this
        console.log(e.target.dataset.type);
        wx.chooseMedia({
            count: 1, // 可选择的图片数量
            mediaType: ['image'],
            sizeType: ['compressed'], // 压缩图片
            sourceType: ['album', 'camera'], // 来源：相册或相机
            success: (res) => {
                console.log(res, '上传图片');
                this.imgeuplode(res.tempFiles[0].tempFilePath)
            }
        })
    },
    /**
     * 上传函数
     */
    imgeuplode(data) {
        wx.showLoading({
            mask: true
        })
        // 获取当前时间戳
        let datatime = new Date().getTime()
        console.log(data);
        let Randomnum = this.getUuid()
        let aecdata
        let md5
        let _that = this
        md5 = encrypt.md5(`sign:data=&nonceStr=${Randomnum}&timestamp=${datatime}`)
        wx.uploadFile({
            url: 'https://api.business.dayenginer.com/user/attachment',
            filePath: data,
            formData: {},
            name: 'file',
            header: {
                "h_uid": wx.getStorageSync('userid') ? wx.getStorageSync('userid') : '',
                "h_timestamp": datatime,
                "h_nonceStr": Randomnum,
                "h_sign": md5,
                "h_token": wx.getStorageSync('token') ? wx.getStorageSync('token') : '',
                "h_deviceId": '',
                'Content-Type': 'multipart/form-data'
            },
            success(res) {
                console.log(res, "上传成功");
                let resone = JSON.parse(encrypt.aesDecrypt(res.data))
                console.log(resone, '上传返回值');
                wx.hideLoading()
                //判断
                if (resone.code == 0) {
                    _that.setData({
                        ['objdata.image']: resone.data.url
                    })
                }



                _that.panduan()
            },
            fail(res) {
                console.log(res, '上传失败');
                console.log(JSON.parse(encrypt.aesDecrypt(res.data)));
                wx.hideLoading()
            }
        })
    },
    getUuid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (Math.random() * 16) | 0,
                v = c == 'x' ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        });
    },
    addshop(e) {
        console.log('增加', e);
        // console.log(this.data.shopjilu.length);
        //进行赋值
        const index1 = this.data.goodslist.findIndex((item) => item.id == e.detail.id)
        if (index1 !== -1) {
            this.data.goodslist[index1].num = e.detail.num
            this.data.goodslist[index1].amout = e.detail.num

        }

        this.setData({
            goodslist: this.data.goodslist
        })
        this.panduan()

        console.log(this.data.goodslist);
    },
    // 判断函数
    hasPositiveNum(arr) {
        return arr.some(item => {
            // 将 num 转换为数值
            const num = Number(item.num);
            // 验证是否为有效数字且 >0
            return !isNaN(num) && num > 0;
        });
    },
    /**
     * 申请退货
     */
    async getmyreturnGoods() {
        wx.showLoading({
            mask: true
        })
        try {
            let res = await api.myreturnGoods({
                ...this.data.objdata,
                goods_list: this.data.goodslist
            })
            console.log(res, '申请反馈');
            if (res.code == 0) {
                wx.hideLoading()
                wx.showToast({
                    title: res.msg,
                    icon: "success",
                    duration: 2000
                })
                setTimeout(() => {
                    wx.navigateBack(1)
                }, 500)
            } else {
                wx.hideLoading()
                wx.showToast({
                    title: res.msg,
                    icon: "error",
                    duration: 2000
                })

            }
        } catch (error) {
            wx.hideLoading()
            wx.showToast({
                title: '请求失败',
            })
        }


    },
    tijiaofagdu: util.throttle(function () {
        this.getmyreturnGoods()
    }, 1000),

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.shopdeteil()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})